# find the differentially booleanized TFs, collect the transcriptional interactions among them,
# prepare the adjacency matrix and the boolean gene expression profiles

source("../scripts/hairballFunctions.r")

args = commandArgs(TRUE)
cutoff=args[1]

threshold = 1-as.double(cutoff)

##############
## hairball ##
##############
pval_expr = read.table("genes_pval.txt",row.names=1,sep="\t")
bool_state = cbind(as.integer(pval_expr[,1]<threshold),as.integer(pval_expr[,2]<threshold))
rownames(bool_state) = rownames(pval_expr)

# define DE genes: opposite boolean state in the 2 conditions
DE = which(bool_state[,1] != bool_state[,2])
print(sprintf("There are %i differentially booleanized genes",length(DE)))
state = bool_state[DE,]
write.table(state,sprintf("DEbool-state-cutoff%s.txt",cutoff),row.names=TRUE,col.names=FALSE,quote=FALSE,sep="\t")

# prepare hairball
hairball = read.table("../data/TransReg_TFHairball.txt",stringsAsFactors=FALSE) # Metacore, directed interactions among all TF/cofactor/chromatin remodeller in AnimalTFDB
treg = unique(c(hairball[,1],hairball[,3]))
pheno = state[which(rownames(state) %in% treg),]
print(sprintf("There are %i TFs in the hairball",nrow(pheno)))
if (nrow(pheno)<10) stop("HAIRBALL IS TOO SMALL, the analysis will not continue")

this_hairball = hairball[which(hairball[,1] %in% rownames(pheno) & hairball[,3] %in% rownames(pheno)),]
this_hairball[,2] = unname(sapply(this_hairball[,2], function(x) switch(x,"Activation"="-->","Inhibition"="--|", "Unspecified"="--?")))
print(sprintf("There are %i interactions in the hairball",nrow(this_hairball)))

write.table(this_hairball,sprintf("tint-DEbool-cutoff%s.txt",cutoff),col.names=FALSE,row.names=FALSE,quote=FALSE,sep=" ") # interactions for visualization, e.g. with Cytoscape

# prepare adjacency matrix and boolean profiles for contextualization
adj_matrix <- tintToAdjmat(sprintf("tint-DEbool-cutoff%s.txt",cutoff),sprintf("adjmat-DEbool-cutoff%s.txt",cutoff))
pheno_red <- pheno[rownames(pheno) %in% rownames(adj_matrix),]
write.table(pheno_red, sprintf("phenored-DEbool-cutoff%s.txt",cutoff), sep="\t",row.names=TRUE,col.names=FALSE,quote=FALSE)


## Prepare cont.m file
cont = sprintf("cont-cutoff%s.m",cutoff)
unlink(cont)
system(paste0("touch ",cont))
l1 = paste0("\"cutoff='",cutoff,"'",";\"")
system(paste0("echo ",l1," >>",cont))
l2 = paste0("\"addpath(", "'../scripts/'" ,");\"")
system(paste0("echo ",l2," >>",cont))
l3 = paste0("contextualize_2attr")
system(paste0("echo ",l3," >>",cont))



